import React, { FC, useState } from 'react';
import { Tabs, Button } from 'choerodon-ui/pro';
import { TabsType } from 'choerodon-ui/lib/tabs/enum';

const { TabPane } = Tabs;

export interface TabsCustomAddTriggerProps {}

type TabItem = {
  title: string;
  key: string;
  content: string;
  closable?: boolean;
}

const TabsCustomAddTrigger: FC<TabsCustomAddTriggerProps> = () => {
  const [tabs, setTabs] = useState<TabItem[]>([
    {title: 'Tab1', key: '1', content: 'Tab Content 1', closable: false},
    {title: 'Tab2', key: '2', content: 'Tab Content 2', closable: true},
    {title: 'Tab3', key: '3', content: 'Tab Content 3', closable: true},
  ]);
  const handleEdit = (targetKey: any, action: any) => {
    console.log(targetKey, action);
    if (action === 'add') {
      setTabs(prev => [...prev, {title: 'new Tab', content: 'new tab content', closable: true, key: Math.random().toString()}] );
    } else if (action === 'remove') {
      setTabs(prev => prev.filter(t => t.key !== targetKey));
    }
  };
  return (
    <>
      <div style={{marginBottom: 8}}>
        <Button icon="add" onClick={() => handleEdit(null, 'add')}>添加</Button>
      </div>
      <Tabs
        hideAdd
        defaultActiveKey="2"
        type={'editable-card' as TabsType}
        onEdit={handleEdit}
      >
        {
          tabs.map(({title, content, key, closable}: TabItem) => (
            <TabPane
              tab={title}
              key={key}
              closable={closable}
            >
              {content}
            </TabPane>
          ))
        }
      </Tabs>
    </>
  );
};

export default TabsCustomAddTrigger;
